<template>
  <div class="details-div">
    <div style="width: 500px;">
      <el-row>
        <el-col>
          <el-card :body-style="{ padding: '0px' }" style="background-color: #cccccc">
            <div style="display: flex;justify-content: space-around">
              <!-- 多张图片处理-->
              <div v-if="form.images.length !== 0">
                <img v-for="item of form.images" style="margin-right: 10px;"
                     :src="item" class="image" width="150px" height="150px"/>&nbsp;
              </div>
              <!-- 单张图片处理-->
              <div v-if="form.images.length === 0">
                <img :src="form.image" class="image" width="150px" height="150px"/>&nbsp;
              </div>
            </div>
            <div style="padding: 14px;display: flex;justify-content: center;align-items: center">
              <span style="margin-left: -220px;">档案标题：</span>
              <el-input v-model="form.title" style="width: 180px;"/>
            </div>
            <div style="padding: 14px;display: flex;justify-content: center;align-items: center">
              <span style="margin-left: -10px;">档案人描述：</span>
              <div class="bottom">
                <textarea cols="55" rows="5" v-model="form.content"></textarea>
              </div>
            </div>
            <div style="padding: 14px;display: flex;justify-content: center;align-items: center">
              <span style="margin-left: -160px;">事件所属类型：</span>
              <div class="bottom" v-for="item of form.channelNames">
                <el-button type="danger" text>{{ item.name }}</el-button>
              </div>
              <el-button type="primary" @click="dialogVisible = true">修改类型</el-button>
            </div>
            <div style="padding: 14px;display: flex;justify-content: center;align-items: center">
              <span style="margin-left: -305px;">档案使用状态：</span>
              <div class="bottom">
                <el-switch
                    v-model="form.enable"
                    class="ml-2"
                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                    :active-value="1"
                    :inactive-value="0"
                />
              </div>
            </div>
            <div style="padding: 14px;display: flex;justify-content: center;align-items: center">
              <span style="margin-left: -150px;">档案发布时间：</span>
              <div class="bottom">
                <div class="block">
                  <el-date-picker
                      v-model="form.publishDate"
                      type="datetime"
                      placeholder="请重新输入发布时间"
                      value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </div>
              </div>
            </div>
            <div style="padding: 14px;display: flex;justify-content: center;align-items: center">
              <span style="margin-left: -200px;">档案审核状态原因：</span>
              <div class="bottom">
                <el-button type="danger" text v-if="form.status === 4">未通过原因：{{ form.remark }}</el-button>
                <el-button type="success" text v-if="form.status === 5">一级审核通过</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <!--  标题展示  -->
    <div class="title-div">
      <img src="../assets/1111111111.jpg" width="100px" height="80px">
      <h2 style="position: absolute;top: 100px;font-size: 32px">民安档案展示</h2>
      <p style="position: absolute;top: 150px;font-size: 20px"><span>档案编号：</span>{{ form.id }}</p>
    </div>
    <!--  对应的视频展示  -->
    <div class="video-div">
      <video :src="form.videoContent" controls width="500px" height="340px"></video>
    </div>
    <!--  对应的手绘图片展示  -->
    <div class="plan-div">
      <el-empty style="width: 500px"
                :image="form.planContent"/>
    </div>
    <!--  小的log图  -->
    <div class="xinku-div">
      <img src="../assets/辛苦了.jpg" width="300px">
    </div>
  </div>
  <div>
    <div style="position: absolute;top: 35px;">
      <el-button plain type="info" style="margin-left: 16px;" @click="voice()">
        语音录入
      </el-button>
      <el-button plain type="success" style="margin-left: 16px" @click="camera()">
        重新拍摄
      </el-button>
      <el-button plain type="danger" style="margin-left: 16px" @click="dialogVisible1 = true">
        修改图片
      </el-button>
      <el-button plain type="primary" style="margin-left: 16px" @click="updateFIles()">
        提交修改
      </el-button>

      <el-drawer v-model="drawer2" title="I am the title" :with-header="false" size="50%">
        <div style="display: flex;justify-content: center;align-items: center;">
          <div style="border: 1px solid black;width: 1200px;height: 350px;
                    border-radius: 10px 10px 10px 10px;background:azure;" v-text="speechDescritpionArr.join(',')">
          </div>
        </div>
        <div style="display: flex;justify-content: center;margin-right: 50px">
          <div class="body-speech">
            <el-button type="success" @click="eanble()">开启录音</el-button>
          </div>
          <div style="width: 100px;" class="body-speech">
            <el-button type="success" @click="downUp()">关闭录音</el-button>
          </div>
          <div style="width: 100px;">
            <el-button type="success" @click="clearText()">清空文本内容</el-button>
          </div>
        </div>
      </el-drawer>
      <el-drawer v-model="drawer3" title="I am the title" :with-header="false" size="50%">
        <div class="container">
          <canvas ref="canvas" width="640" height="360"></canvas>
          <video class="video-luzhi" ref="video" autoplay loop muted></video>
          <div class="button-group">
            <el-button type="success" @click="startRecording">开始录制</el-button>
            <el-button type="danger" @click="stopRecording" :disabled="!isRecording">结束录制</el-button>
          </div>
        </div>
      </el-drawer>

    </div>
  </div>

  <!-- 类型修改弹窗 -->
  <el-dialog
      v-model="dialogVisible"
      title="案件类型转换"
      width="500"
  >
    <el-select
        v-model="form.channels"
        multiple
        placeholder="Select"
        style="width: 240px"
    >
      <el-option
          v-for="item in options"
          :key="item.id"
          :label="item.name"
          :value="item.id"
      />
    </el-select>
  </el-dialog>


<!-- 修改图片弹窗 -->
  <el-dialog
      v-model="dialogVisible1"
      width="500"
  >
    <el-upload
        v-model:file-list="images"
        action="/api/api/files/upload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :headers="{'Authorization':token}"
    >
      <el-icon>
        <Plus/>
      </el-icon>
    </el-upload>

    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image"/>
    </el-dialog>
  </el-dialog>

</template>

<script setup>
import {ref, onBeforeUnmount, onUnmounted, nextTick} from 'vue';
import {useRoute} from 'vue-router';
import CryptoJS from 'crypto-js';
import {detalisSelectJs, updateSearchJs} from "../api/files/files.js";
import {channelListJs} from "../api/channel/channel.js";
import {ElMessage} from "element-plus";
import {enableJs, shutdownJs} from "../api/speech/speech.js";
import axios from "axios";
import router from "../router/index.js";

// 获取路由参数中的 id  并进行一个解密
const route = useRoute();
const val = route.query.val;
const secretKey = 'mySecretKey123';
const bytes = CryptoJS.AES.decrypt(val, secretKey);
const decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
const token = localStorage.getItem("token")
// 定义接受参数表单
const form = ref({
  filesId:null,
  images: [],
  title: null,
  content: null,  // 基本描述内容
  status: null,
  publishDate: null,
  vedioImg: null,
  channels:[],  // 类型集合id,
  enable:null,
  imageUrl:[],
  speechContent:null
});
const speechDescritpionArr = ref([]) // 语音转换文字数组
const images = ref([]) // 存储图文图片
const imageArr = ref([])

// 查询详情数据
function showDetalis() {
  detalisSelectJs(decryptedData).then(res => {
    if (res.data.code === 200) {
      form.value = res.data.data;
      form.value.enable = parseInt(res.data.data.enable)
    }
  });
}

showDetalis()
// 修改类型弹窗
const dialogVisible = ref(false)
const options = ref([])

// 查询类型弹窗
function filesTypesList() {
  channelListJs().then(res => {
    if (res.data.code == 200) {
      options.value = res.data.data
    }
  })
}

filesTypesList()

// 二大组件修改
const drawer2 = ref(false)
const drawer3 = ref(false)
// 语音录入
// 语音转换文字
function voice() {
  drawer2.value = true
}

// 定义数组
// WebSocket 实例
const socket = ref(null);
// 存储 WebSocket 消息
const messages = ref([]);

// 创建 WebSocket 连接
const connectWebSocket = () => {
  socket.value = new WebSocket('ws://localhost:8081/websocket');

  // WebSocket 打开连接时
  socket.value.onopen = () => {
    console.log('WebSocket 连接已打开');
  };

  // WebSocket 接收到消息时
  socket.value.onmessage = (event) => {
    console.log('收到消息:', event.data);
    messages.value.push(event.data);
    speechDescritpionArr.value.push(event.data)  // 接受语音转换文字数据
  };

  // WebSocket 错误时
  socket.value.onerror = (error) => {
    console.error('WebSocket 错误:', error);
  };

  // WebSocket 连接关闭时
  socket.value.onclose = () => {
    console.log('WebSocket 连接已关闭');
  };
};
// 组件卸载时关闭 WebSocket 连接
onBeforeUnmount(() => {
  if (socket.value) {
    socket.value.close();
  }
});

// 开启语音录制
function eanble() {
  // 点击之后开启websocket连接
  connectWebSocket();
  enableJs()
  ElMessage.success("开启成功")
}

// 关闭录音
function downUp() {
  shutdownJs()
  ElMessage.success("关闭成功")
}

// 清空文本内容
function clearText() {
  speechDescritpionArr.value = []
}

// 摄像头
// 摄像头
// 定义响应式数据
const canvas = ref(null);
const video = ref(null);
const isRecording = ref(false);
const canRecord = ref(false);
const chunks = ref([]);

let frameId = null;
let recorder = null;
// 新增变量用于记录录制器的状态（'recording' 录制中，'paused' 暂停中，'stopped' 停止）
const recorderState = ref('stopped');

let videoWidth = 848;
let videoHeight = 480;
const frameRate = 24; // 调整帧率
const encodeType = "video/webm;codecs=opus"; // 尝试使用不同的编码格式

// 绘制帧的函数
const drawFrame = () => {
  const canvasContext = canvas.value.getContext("2d");
  canvasContext.drawImage(video.value, 0, 0, videoWidth, videoHeight);
  frameId = requestAnimationFrame(drawFrame);
};

// 开始录制的函数
const startRecording = () => {
  isRecording.value = true;
  canRecord.value = false;
  recorderState.value = 'recording';

  // 清空之前的录制数据
  chunks.value = [];

  // 请求音频权限
  navigator.mediaDevices.getUserMedia({
    audio: true,
    video: true
  }).then(mediaStream => {
    video.value.srcObject = mediaStream;
    video.value.play();

    // 获取视频流的实际尺寸
    video.value.addEventListener('loadedmetadata', () => {
      videoWidth = video.value.videoWidth;
      videoHeight = video.value.videoHeight;
      canvas.value.width = videoWidth;
      canvas.value.height = videoHeight;

      // 创建一个新的媒体流，包含视频和音频轨道
      const combinedStream = new MediaStream([...mediaStream.getTracks(), ...canvas.value.captureStream(frameRate).getTracks()]);
      recorder = new MediaRecorder(combinedStream, {
        mimeType: encodeType
      });

      recorder.ondataavailable = e => {
        chunks.value.push(e.data);
      };

      recorder.start(10);
      drawFrame();
    });
  }).catch(error => {
    alert("打开摄像头或麦克风失败");
    isRecording.value = false;
    canRecord.value = true;
    recorderState.value = 'stopped';
  });
};

// 停止录制的函数
const stopRecording = () => {
  isRecording.value = false;
  canRecord.value = true;
  recorderState.value = 'stopped';
  if (recorder) {
    recorder.stop();
  }
  cancelAnimationFrame(frameId);
  download();

  // 重置状态变量
  chunks.value = [];
  frameId = null;
  recorder = null;

  // 停止媒体流
  if (video.value && video.value.srcObject) {
    const tracks = video.value.srcObject.getTracks();
    tracks.forEach(track => track.stop());
    video.value.srcObject = null;
  }
};

// 下载函数
const download = async () => {
  const blob = new Blob(chunks.value, {type: encodeType});
  const fileName = new Date().getTime() + ".webm";
  // 创建FormData对象，用于上传文件
  const formData = new FormData();
  formData.append('video', blob, fileName);
  form.value.vedioImg = formData
  try {
    const token = localStorage.getItem("token");
    // 发送POST请求到后端接口，这里假设后端接口地址是'/api/uploadVideo'，根据实际情况调整
    const response = await axios.post('/api/api/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        ' Authorization': `Bearer ${token}`,
      }
    });
    console.log('视频文件已成功发送到后端，后端返回信息：', response.data);
  } catch (error) {
    console.error('发送视频文件到后端出错：', error);
  }
};


// 抽屉摄像头打开
function camera() {
  drawer3.value = true
  navigator.mediaDevices.getUserMedia({
    audio: false,
    video: true
  }).then(mediaStream => {
    nextTick(() => {
      if (video.value) { // 确保 video 元素已经被渲染
        video.value.srcObject = mediaStream;
        video.value.play();
      } else {
        console.error('Video element not found');
        ElMessage.error('视频元素未找到');
      }
    });
  }).catch(error => {
    console.error('打开摄像头失败，具体错误信息：', error);
    ElMessage.error('打开摄像头失败');
  });
}

// 组件卸载时执行的逻辑
onUnmounted(() => {
  if (recorder && recorder.state !== 'inactive') {
    recorder.stop();
  }
  if (video.value && video.value.srcObject) {
    const tracks = video.value.srcObject.getTracks();
    tracks.forEach(track => track.stop());
    video.value.srcObject = null;
  }
});
// 对外暴露的数据和方法
defineExpose({
  canvas,
  video,
  isRecording,
  canRecord,
  startRecording,
  stopRecording,
  recorderState,
});

// 修改图片
const dialogVisible1 = ref(false)
const dialogImageUrl = ref('')

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}

// 修改档案
function updateFIles() {
  // 集合图片处理
  images.value.forEach(el=>{
    imageArr.value.push(el.name)
  })
  form.value.imageUrl = imageArr.value
  form.value.speechContent = speechDescritpionArr._value.toString()
  form.value.filesId = BigInt(decryptedData).toString()
  console.log(speechDescritpionArr._value.toString() + "speechContent--------")
  // 对id做一个处理
  form.value.id = parseInt("0")
  updateSearchJs(form.value).then(res=>{
    if(res.data.code == 200){
      ElMessage.success("修改成功")
      // 跳转到档案查询
      router.push("/editWare")
    }else{
      ElMessage.error("修改失败")
    }
  })
}


</script>

<style>
.details-div {
  background-color: #cccccc;
  width: 100%;
  height: 90vh;
  border: 1px solid black;
  position: relative;
}

.video-div {
  width: 500px;
  height: 340px;
  position: absolute;
  top: -1px;
  right: 80px;
}

.title-div {
  display: flex;
  justify-content: center;
  width: 350px;
  height: 340px;
  position: absolute;
  top: -1px;
  right: 600px;
}

.plan-div {
  width: 500px;
  height: 260px;
  position: absolute;
  bottom: -10px;
}

.xinku-div {
  width: 500px;
  height: 340px;
  position: absolute;
  right: 100px;
  bottom: 1px;
}

.body-speech {
  width: 100px;
  margin-right: 40px;
}

upload-body {
  font-family: Arial, sans-serif;
  background-color: #f4f4f4;
  height: 70vh;
}

.body-speech {
  width: 100px;
  margin-right: 40px;
}

canvas {
  display: none;
}

.video-luzhi {
  width: 848px;
  height: 480px;
  background: darkblue;
  display: block;
  border-radius: 2px;
  box-shadow: 0 1px 1.5px 1px rgba(0, 0, 0, 0.12);
  margin-top: -250px;
}

button:last-child[disabled] {
  background: gray;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 80vh;
}

canvas {
  border: 2px solid #ccc;
  background-color: #fff;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease-in-out;
  margin-top: 60px; /* Adjust based on controls height */
  width: 100%;
  max-width: 800px;
  height: calc(100vh - 80px); /* Full height minus control panel height */
}

canvas:hover {
  transform: scale(1.02);
}

@media (max-width: 768px) {
  canvas {
    height: calc(100vh - 100px); /* Adjust for smaller screens */
  }
}

</style>